package com.coolwen.controller;

import com.alibaba.fastjson.JSON;
import com.coolwen.entity.Group;
import com.coolwen.entity.Order;
import com.coolwen.entity.User;
import com.coolwen.entity.UserGroup;
import com.coolwen.service.*;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by Eoly on 2016/12/7.
 */
@Controller
@SessionAttributes("loginUser")
@RequestMapping("/")
public class GroupController {

    @Autowired
    GoodsTypeService goodsTypeService;

    @Autowired
    GroupService groupService;

    @Autowired
    UserGroupService userGroupService;

    @Autowired
    OrderService orderService;

    @Autowired
    UserService userService;

    /**
     *
     * @param loginUser
     * @param model
     * @return
     */
    @RequestMapping("/login-user/group")
    public String showGroupById(@ModelAttribute("loginUser") User loginUser, Model model,@RequestParam Integer groupId) {
        //获得团详情
        Group group = groupService.findByGroupId(groupId);
        group.setNowUserNumber(userGroupService.getTheNumberGroupJoined(group.getGroupId()));
        model.addAttribute("group", group);
        UserGroup userGroup = new UserGroup();
        userGroup.setUserId(loginUser.getUserId());
        userGroup.setGroupId(groupId);
        if (userGroupService.findIdByRequestId(userGroup).size() == 1) {
            model.addAttribute("meg", "您已参团");
        }
        System.out.println(JSON.toJSON(groupService.findByGroupId(groupId)));
        return "/web/good_info";
    }

    /**
     * 查询用户所有的团列表
     *
     * @param loginUser
     * @param model
     * @return
     */
    @RequestMapping("/login-user/my-group-list")
    public String showGroupList(@ModelAttribute("loginUser") User loginUser, Model model) {

        //获得团列表
        List<Group> myGroups = groupService.findByInitiatorId(loginUser.getUserId());
        List<Group> joinedGroups = groupService.findByUserId(loginUser.getUserId());
        List<Group> myGroupList = new ArrayList<Group>();
        List<Group> joinedGroupList = new ArrayList<Group>();

        //获得参团人数
        for(Group group:myGroups){
            group.setNowUserNumber(userGroupService.getTheNumberGroupJoined(group.getGroupId()));
            myGroupList.add(group);
        }
        for(Group group:joinedGroups){
            group.setNowUserNumber(userGroupService.getTheNumberGroupJoined(group.getGroupId()));
            joinedGroupList.add(group);
        }

        //放入发起者发起的团列表
        model.addAttribute("myGroupList", myGroupList);
        //放入加入的团列表
        model.addAttribute("joinedGroupList", joinedGroupList);
        return "/web/allteam";
    }

    /**
     * 查询用户所有开团成功的团
     *
     * @param loginUser
     * @param model
     * @return
     */
    @RequestMapping("/login-user/my-group-opened")
    public String showGroupListOpened(@ModelAttribute("loginUser") User loginUser, Model model) {

        //获得团列表
        List<Group> myGroups = groupService.findByStateAndInitiatorId(2, loginUser.getUserId());
        List<Group> joinedGroups = groupService.findByStateAndUserId(2, loginUser.getUserId());
        List<Group> myGroupList = new ArrayList<Group>();
        List<Group> joinedGroupList = new ArrayList<Group>();

        //获得参团人数
        for(Group group:myGroups){
            group.setNowUserNumber(userGroupService.getTheNumberGroupJoined(group.getGroupId()));
            myGroupList.add(group);
        }
        for(Group group:joinedGroups){
            group.setNowUserNumber(userGroupService.getTheNumberGroupJoined(group.getGroupId()));
            joinedGroupList.add(group);
        }

        //放入发起者发起的团列表
        model.addAttribute("myGroupList", myGroupList);
        //放入加入的团列表
        model.addAttribute("joinedGroupList", joinedGroupList);
        return "/web/opened";
    }

    /**
     * 查询用户所有开团中的团
     *
     * @param loginUser
     * @param model
     * @return
     */
    @RequestMapping("/login-user/my-group-opening")
    public String showGroupListOpening(@ModelAttribute("loginUser") User loginUser, Model model) {

        //获得团列表
        List<Group> myGroups = groupService.findByStateAndInitiatorId(1, loginUser.getUserId());
        List<Group> joinedGroups = groupService.findByStateAndUserId(1, loginUser.getUserId());
        List<Group> myGroupList = new ArrayList<Group>();
        List<Group> joinedGroupList = new ArrayList<Group>();

        //获得参团人数
        for(Group group:myGroups){
            group.setNowUserNumber(userGroupService.getTheNumberGroupJoined(group.getGroupId()));
            myGroupList.add(group);
        }
        for(Group group:joinedGroups){
            group.setNowUserNumber(userGroupService.getTheNumberGroupJoined(group.getGroupId()));
            joinedGroupList.add(group);
        }

        //放入发起者发起的团列表
        model.addAttribute("myGroupList", myGroupList);
        //放入加入的团列表
        model.addAttribute("joinedGroupList", joinedGroupList);
        return "/web/opening";
    }

    /**
     * 获取指定类型的所有团
     *
     * @param typeId 类型id
     * @return 存放团的列表的JSON对象
     */
    @ResponseBody
    @RequestMapping(value = "/group-list", produces = "text/html;charset=UTF-8")
    public String getGroupList(@RequestParam Integer typeId) {
        List<Group> groups = groupService.findByTypeId(typeId);
        return JSON.toJSON(groups).toString();
    }

    /**
     * 跳转到开团页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "login-user/turn-add", produces = "text/html;charset=UTF-8")
    public String turnToAdd(Model model) {


        model.addAttribute("types", goodsTypeService.findAllGoodsType());

        //跳转到团提交页面
        return "/web/open_team";
    }


    /**
     * 参加团
     *
     * @param loginUser
     * @param model
     * @param groupId
     * @return
     */
    @RequestMapping(value = "login-user/group-join", produces = "text/html;charset=UTF-8")
    public String joined(@ModelAttribute("loginUser") User loginUser, Model model, @RequestParam Integer groupId) {

        //获得团实体
        Group group = groupService.findByGroupId(groupId);

        //判断用户是否已经加入,判断团状态
        UserGroup userGroup = new UserGroup();
        userGroup.setGroupId(groupId);
        userGroup.setUserId(loginUser.getUserId());
        List<UserGroup> userGroupGetted = userGroupService.findIdByRequestId(userGroup);
        System.out.println(JSON.toJSON(userGroupGetted));
        if (userGroupGetted.size()!=0 || group.getGroupState() != 1) {
            return "redirect:/login-user/index";
        }

        //提交数据到数据库
        userGroupService.addUserGroup(userGroup);


        //更新参加人数和团状态
        Integer numberInGroup = userGroupService.getTheNumberGroupJoined(groupId);
        model.addAttribute("numberInGroup", numberInGroup);

        if (group.getGroupTargetNumber() <= numberInGroup) {
            group.setGroupState(2);
            groupService.updateGroupByGroupId(group);
            //生成订单
            List<User> users = userService.findByGroupId(group.getGroupId());
            for (User user : users) {
                Order order = new Order();
                order.setGroupId(groupId);
                order.setUserId(user.getUserId());
                orderService.addOrder(order);
            }
        }
        return "redirect:/login-user/group?groupId="+groupId;
    }


    /**
     * 提交团列表
     *
     * @param loginUser
     * @param groupTitle
     * @param groupDetail
     * @param price
     * @param priceOriginal
     * @param groupTargetNumber
     * @param typeId
     * @param image
     * @param req
     * @return
     */
    @RequestMapping(value = "login-user/group-add", produces = "text/html;charset=UTF-8", method = RequestMethod.POST)
    public String addGroup(
            @ModelAttribute("loginUser") User loginUser,
            @RequestParam String groupTitle,
            @RequestParam String groupDetail, @RequestParam Double price,
            @RequestParam Double priceOriginal,
            @RequestParam Integer groupTargetNumber,
            @RequestParam Integer typeId,
            @RequestParam MultipartFile image,
            HttpServletRequest req
    ) {
        //获取当前路径
        String realPath = req.getSession().getServletContext().getRealPath("/resources/images");
        System.out.println(realPath);
        String imgAddress = null;
        Group group = new Group();
        System.out.println(image.getName() + "---" + image.getContentType() + "---" + image.getOriginalFilename());
        try {
            if (!image.isEmpty()) {

                //以当前时间加随机数命名上传文件
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS");
                String date = sdf.format(new java.util.Date());
                String originalFilename = image.getOriginalFilename();
                imgAddress = date + new Random().nextInt() + originalFilename.substring(originalFilename.lastIndexOf('.'));
                System.out.println(imgAddress);

                //将文件上传到服务器
                File f = new File(realPath + "/" + imgAddress);
                FileUtils.copyInputStreamToFile(image.getInputStream(), f);

//                    //使用StreamsAPI方式拷贝文件
//                    Streams.copy(image.getInputStream(), new FileOutputStream("E:/temp/" + image.getOriginalFilename()), true);
            } else return "redirect:/login-user/index";
        } catch (IOException e) {
            e.printStackTrace();
            return "redirect:/login-user/index";
        }
        group.setGroupTitle(groupTitle);
        group.setGroupDetail(groupDetail);
        group.setPrice(price);
        group.setPriceOriginal(priceOriginal);
        group.setGroupTargetNumber(groupTargetNumber);
        group.setTypeId(typeId);
        group.setImgAddress(imgAddress);
        group.setGroupInitiatorId(loginUser.getUserId());

        groupService.addGroup(group);

        return "redirect:/login-user/index";
    }
}
